package com.vivo.tasks;

import com.thinkgem.jeesite.common.utils.IdGen;
import com.thinkgem.jeesite.common.utils.StringUtils;
import com.thinkgem.jeesite.modules.sys.dao.UserDao;
import com.thinkgem.jeesite.modules.sys.entity.Office;
import com.thinkgem.jeesite.modules.sys.entity.User;
import com.thinkgem.jeesite.modules.sys.service.OfficeService;
import com.thinkgem.jeesite.modules.sys.service.SystemService;
import com.vivo.Utils.CommonUtils;
import com.vivo.Utils.SysUtils;
import com.vivo.common.DatabaseContextHolder;
import com.vivo.dealer.entity.ViUserDealerPrivilege;
import com.vivo.dealer.service.ViUserDealerPrivilegeService;
import com.vivo.employee.entity.ViEmployee;
import com.vivo.employee.service.ViEmployeeService;
import com.vivo.fx.employee.entity.FxEmployeeinfo;
import com.vivo.fx.employee.service.FxEmployeeinfoService;
import com.vivo.fx.entity.SysUserdealerprivilege;
import com.vivo.fx.service.SysUserdealerprivilegeService;
import com.vivo.fx.sys.entity.FxUserinfo;
import com.vivo.fx.sys.service.FxUserinfoService;
import com.vivo.system.entity.SysUserrole;
import com.vivo.system.entity.ViSysRoleMap;
import com.vivo.system.service.FxSysService;
import com.vivo.system.service.SysUserroleService;
import com.vivo.system.service.ViSysRoleMapService;
import com.vivo.tasks.vivofx.Helper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class TaskUpdUser {
    @Autowired
    private ViEmployeeService viEmployeeService;

    @Autowired
    private FxEmployeeinfoService fxEmployeeinfoService;

    @Autowired
    private SystemService systemService;

    @Autowired
    private OfficeService officeService;

    @Autowired
    private ViSysRoleMapService viSysRoleMapService;

    @Autowired
    private FxUserinfoService fxUserinfoService;

    @Autowired
    private ViUserDealerPrivilegeService viUserDealerPrivilegeService;

    @Autowired
    private SysUserroleService sysUserroleService;

    @Autowired
    private SysUserdealerprivilegeService sysUserdealerprivilegeService;

    @Autowired
    private FxSysService fxSysService;

    @Autowired
    private UserDao userDao;

    public void SyncData() {
        getNeedUpdEmp();
    }


    /**
     * 同步用户权限信息
     */
    public void SyncPrivData() {
        getNeedUpdPriv();
    }

    private void getNeedUpdPriv() {
        List<User> needUpdList = userDao.getNeedUpdList();
        if (needUpdList.size() == 0) {
            System.out.println("没有需要进行更新的用户权限信息。。");
            return;
        }

        for (User user : needUpdList) {
            Office comp = officeService.get(user.getCompany().getId());
            Office topComp = officeService.getTopComp(comp);
            String zone = topComp.getName().contains("安徽") ? "ah" : "js";

            // 查找用户权限列表
            List<ViUserDealerPrivilege> privilegeList = viUserDealerPrivilegeService.getListByUserId(user.getId());

            handlerUpdPriv(user, zone, privilegeList);
        }
    }

    private boolean handlerUpdPriv(User user, String zone, List<ViUserDealerPrivilege> privilegeList) {
        boolean retFlag = false;
        FxUserinfo fxUser = null;

        do {
            try {
                // 根据区域切换数据库
                Helper.changeDB(zone);

                // 同步员工、用户、用户角色 等信息
                fxUser = fxUserinfoService.get(user.getId());
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            }finally {
                DatabaseContextHolder.setMainDb();
            }

            // 远程不存在用户信息，设置状态为7 方便之后查找
            if (fxUser == null) {
                user.setUpdStatus("7");
                user.setUpdStatusDate(new Date());
                userDao.updateUserInfo(user);
                continue;
            }

            List<SysUserdealerprivilege> userdealerprivilegeList = new ArrayList<SysUserdealerprivilege>();
            for (ViUserDealerPrivilege viPri: privilegeList) {
                SysUserdealerprivilege sysUserdealerprivilege = new SysUserdealerprivilege();
                sysUserdealerprivilege.setUserid(user.getId());
                sysUserdealerprivilege.setDealerrelationid(viPri.getDealerRelationId());
                sysUserdealerprivilege.setDealerprivilegekind(viPri.getDealerPrivilegeKind());
                sysUserdealerprivilege.setDealerprivilegeid(IdGen.uuid());
                userdealerprivilegeList.add(sysUserdealerprivilege);
            }

            try {
                // 根据区域切换数据库
                Helper.changeDB(zone);

                fxSysService.syncPrivToSys(fxUser, userdealerprivilegeList);
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            } finally {
                DatabaseContextHolder.setMainDb();
            }

            // 远程存在用户信息，设置状态为0 同步成功
            if (fxUser == null) {
                user.setUpdStatus("0");
                user.setUpdStatusDate(new Date());
                userDao.updateUserInfo(user);
                continue;
            }

            retFlag = true;
        } while (false);

        return retFlag;
    }

    /**
     * 获取所有需要进行更新的员工信息
     * method： 通过查找员工表中的upd字段
     */
    public void getNeedUpdEmp() {
        ViEmployee veQuery = new ViEmployee();
        veQuery.setUpdStatus("3"); // 需要同步

        List<ViEmployee> needUpdVeList = viEmployeeService.findList(veQuery);
        if (needUpdVeList.size() == 0) {
            System.out.println("没有需要进行更新的员工信息。。。");
            return;
        }

        System.out.println("开始同步用户信息。。。");

        boolean isJianzhi = false;

        for (ViEmployee ve:needUpdVeList) {
            // 查看是否是总部兼职信息
            if (ve.getComp().getId().equals("1")) {
                List<ViEmployee> veList = viEmployeeService.getAllById(ve.getId());
                // 存在总部之外的兼职信息
                if (veList != null && veList.size() == 2) {
                    for (ViEmployee viEmployee : veList) {
                        if (!viEmployee.getComp().getId().equals("1")) {
                            ve.setComp(viEmployee.getComp());
                            ve.setDept(viEmployee.getDept());
                            ve.setPost(viEmployee.getPost());
                            ve.setPostName(viEmployee.getPost().getName());

                            // 存在总部兼职信息
                            isJianzhi = true;
                        }
                    }
                }

                // 未修改兼职信息， 或者兼职信息只是IDC总部内部之间的兼职
                if (ve.getComp().getId().equals("1")) {
                    exitAndSaveVe(ve, "4");
                    continue;
                }
            }


            Office comp = officeService.get(ve.getComp().getId());
            Office topComp = officeService.getTopComp(comp);
            String zone = topComp.getName().contains("安徽") ? "ah" : "js";

            boolean hasRoleMap = true;
            boolean onlyUpdVeFlag = false;

            if (ve.getTelephone().length() < 11) {
                exitAndSaveVe(ve, "8");
            }

            // 查找用户信息
            User user = systemService.getUserByEmpId(ve.getId());
            // 不符合条件的，修改一下更新状态即可
            if (user == null) {
                exitAndSaveVe(ve, "0");
                System.out.println("找不到对应的用户信息！：" + ve.getName());
                continue;
            }

            // 查找IDC同步记录

            List<ViSysRoleMap> viSysRoleMapList = new ArrayList<ViSysRoleMap>();
            if (ve.getPostName() != null) {
                Map<String, Boolean> postNameMap = new HashMap<String, Boolean>();

                ViSysRoleMap viSysRoleMap = viSysRoleMapService.getByViPostNameAndZone(ve.getPostName(), zone);
                if (viSysRoleMap != null) {
                    postNameMap.put(ve.getPostName(), true);
                    viSysRoleMapList.add(viSysRoleMap);

                    // 只有主岗位有效，才进行设置兼职或者 岗位明细
                    if (ve.getPostDetail() != null && ve.getPostDetail().trim().equals("系统管理员")) {
                        ViSysRoleMap newRoleMap = viSysRoleMapService.getByViPostNameAndZone(ve.getPostDetail().trim(), zone);
                        if (newRoleMap != null && postNameMap.get(ve.getPostDetail().trim()) == null) {
                            viSysRoleMapList.add(newRoleMap);
                            postNameMap.put(ve.getPostDetail().trim(), true);
                        }
                    }

                    // TODO 兼职角色设置
                    List<ViEmployee> veList = viEmployeeService.getAllById(ve.getId());
                    // 存在总部之外的兼职信息
                    if (veList != null && veList.size() > 1) {
                        for (ViEmployee viEmployee : veList) {
                            // 是否是当前的岗位
                            Office tmpPost = officeService.get(viEmployee.getPost().getId());
                            if (tmpPost != null) {
                                ViSysRoleMap newRoleMap = viSysRoleMapService.getByViPostNameAndZone(tmpPost.getName().trim(), zone);
                                if (newRoleMap != null && postNameMap.get(tmpPost.getName().trim()) == null) {
                                    viSysRoleMapList.add(newRoleMap);
                                    postNameMap.put(tmpPost.getName().trim(), true);
                                }
                            }
                        }
                    }
                }
            }

            // 不符合条件的，修改一下更新状态即可
            if (viSysRoleMapList.size() == 0) {
                exitAndSaveVe(ve, "0");
                System.out.println("找不到对应的者岗位映射信息！：" + ve.getName() + "。 系统将只更新用户权限信息！请及时补充岗位映射信息！");
                hasRoleMap = false;
            }

            FxUserinfo fxUserinfo = null;
            FxEmployeeinfo fxEmpinfo = null;
            try {
                // 根据区域切换数据库
                Helper.changeDB(zone);

                fxEmpinfo = fxEmployeeinfoService.get(ve.getId());
                fxUserinfo = fxUserinfoService.get(user.getId());
            } finally {
                DatabaseContextHolder.setMainDb();
            }


            // TODO 判读该用户是不是id为全部小写，如果是则为IDC本地用户
            // 1. 根据身份证查找用优信通是否存在，如果存在则需要替换本地IDC中的员工ID和用户ID
            //判读员工ID是否为小写
            // 添加兼职用户信息过滤
            if (!isJianzhi) {
                String regex = ".*[a-z]+.*";
                Matcher m = Pattern.compile(regex).matcher(ve.getId());
                Matcher um = Pattern.compile(regex).matcher(user.getId());

                boolean isUpdSuccess = true;
                //如果不包含小写字母，则退出
                if (m.matches() && fxEmpinfo == null) {
                    isUpdSuccess = findYxtSamePeople(ve, user, zone, viSysRoleMapList);
                } else if(um.matches() && fxUserinfo == null && fxEmpinfo != null) {
                    // 如果用户uid为小写，只需要需要同步用户uid信息
                    if (ve.getCurStateId().equals("2")) {
                        isUpdSuccess = onlyUpdUser(ve, user, zone, viSysRoleMapList);
                    }
                }

                // 员工离职，只同步员工信息
                if (ve.getCurStateId().equals("1")) {
                    onlyUpdVeFlag = true;
                }

                if (!isUpdSuccess && !onlyUpdVeFlag) {
                    exitAndSaveVe(ve, "7");
                    continue;
                }
            }

            // 查找用户权限列表
            List<ViUserDealerPrivilege> privilegeList = viUserDealerPrivilegeService.getListByUserId(user.getId());

            if (hasRoleMap) {
                // 根据岗位映射，查询当前员工时间
//                Office sysComp = officeService.getVivoOffice(ve.getComp().getId());
                Office sysComp = officeService.getVivoCompany(comp.getName());
                if (sysComp == null) {
                    exitAndSaveVe(ve, "4");
                    System.out.println("找不到对应的二级信息！：" + ve.getName());
                    continue;
                }

                Office sysPost = new Office();
                sysPost.setParent(sysComp);
                sysPost.setName(viSysRoleMapList.get(0).getSysPostName());
                List<Office> postList = officeService.findVivoList(sysPost);
                sysPost = postList.size() > 0 ? postList.get(0) : null;

                if (sysPost == null) {
                    exitAndSaveVe(ve, "4");

                    System.out.println("找不到对应的员工岗位信息！：" + ve.getName());
                    continue;
                }

                Office sysDept = officeService.getVivoSuperDept(sysPost);
                if (sysDept == null) {
                    exitAndSaveVe(ve, "4");
                    System.out.println("找不到对应的员工部门信息！：" + ve.getName());
                    continue;
                }

                // 修改用户的公司、部门、和岗位信息为优信通信息
                ve.setComp(sysComp);
                ve.setDept(sysDept);
                ve.setPost(sysPost);
            }

            // 只更新员工信息
            if (onlyUpdVeFlag) {
                boolean updStatus = false;

                try {
                    // 根据区域切换数据库
                    Helper.changeDB(zone);

                    // 同步员工、用户、用户角色 等信息
                    updStatus = onlyUpdVe(ve, hasRoleMap, zone);
                } finally {
                    DatabaseContextHolder.setMainDb();
                }

                if (updStatus) {
                    exitAndSaveVe(ve, "2");
                    continue;
                }
            }

            // 设置新用户密码和密码盐
            if (StringUtils.isBlank(user.getSysSalt()) || StringUtils.isBlank(user.getSysPwd())) {
                String password = ve.getTelephone().substring(5, 11);
                user.setSysSalt(SysUtils.createSalt());
                user.setSysPwd(SysUtils.getPwdBySalt(password, user.getSysSalt()));
            }

            boolean retFlag = true;
            try {
                // 根据区域切换数据库
                Helper.changeDB(zone);

                // 同步员工、用户、用户角色 等信息
                retFlag = updVeAndUser(ve, user, viSysRoleMapList, privilegeList, hasRoleMap, zone);
            } finally {
                DatabaseContextHolder.setMainDb();
            }

            if (ve != null) {
                if (retFlag) {
                    // 已经同步成功
                    exitAndSaveVe(ve, "2");
                } else {
                    exitAndSaveVe(ve, "4");
                }
            }
        }
    }

    /**
     * 推出并保存内容
     * @param oldVe
     * @param updStatus
     */
    private void exitAndSaveVe(ViEmployee oldVe, String updStatus) {
        // 这里要重新获取员工信息再保存
        ViEmployee tmpVe = viEmployeeService.get(oldVe.getId());

        tmpVe.setUpdStatus(updStatus);
        tmpVe.setSysUpdDate(new Date());
        viEmployeeService.save(tmpVe);
    }

    /**
     * 同步员工和用户信息，以及用户角色信息
     */
    private boolean updVeAndUser(ViEmployee ve, User user, List<ViSysRoleMap> roleMapList,
                                 List<ViUserDealerPrivilege> privilegeList, boolean hasRoleMap, String zone) {

        // TODO  同步员工信息
        FxEmployeeinfo fxEmp = null;
        if (hasRoleMap) {
            fxEmp = fxEmployeeinfoService.get(ve.getId());
            if (fxEmp == null) {
                fxEmp = new FxEmployeeinfo();
                fxEmp.setCreatetime(new Date());
                fxEmp.setIsTaskInsert(true);
                fxEmp.setIsNewRecord(true);
            }

            // 设置假的ID, 原来的表里面没有这个字段
            fxEmp.setId(IdGen.uuid());

            fxEmp.setRemark(ve.getRemarks());

            fxEmp.setCompanyid(ve.getComp().getId());
            fxEmp.setDepartmentid(ve.getDept().getId());
            fxEmp.setPositionid(ve.getPost().getId());

            fxEmp.setEmployeeid(ve.getId());

            // 生成员工ID TODO 填写生成规则
            fxEmp.setEmployeecode(ve.getCode());

            fxEmp.setEmployeename(ve.getName());

            // 添加二级前缀
//            fxEmp.setEmployeename(ve.getComp().getName() + ve.getName());

            fxEmp.setSex(ve.getSex());
            fxEmp.setEducationid(ve.getEducateId());

            fxEmp.setAge(ve.getAge());
            fxEmp.setBirthdaydate(ve.getBirthDate());
            fxEmp.setMaritalstatus(ve.getMaritalStatus());
            String telephone = ve.getTelephone();
            if (telephone.length() > 11 && telephone.contains("-a")) {
                telephone = ve.getTelephone().substring(0, 11);
            }
            fxEmp.setTelephone(telephone);
            fxEmp.setIndutydate(ve.getIndutyDate());
            fxEmp.setChangeformaldate(ve.getOndutyDate());  // 转正日期字段
            fxEmp.setOutdutydate(ve.getOutdutyDate());
            fxEmp.setEmployeecurrstateid(ve.getCurStateId());
            fxEmp.setIdentitycard(ve.getIdentityCard());
            fxEmp.setAddress(ve.getAddress());
            if (ve.getSp() != null && ve.getSp().getId() != null) {
                fxEmp.setSuperioremployeeid(ve.getSp().getId());
            }

            fxEmp.setEmployeeattribute(ve.getDgAttribute());
            if (StringUtils.isBlank(fxEmp.getEmployeeattribute())) {
                fxEmp.setEmployeeattribute(CommonUtils.getDgAttr(ve.getPostName(), ve.getEmpAttribute()));
            }
            fxEmp.setBirthdaydatetype("1");
            // 设置农历时间 TODO

            fxEmp.setCensusregister(ve.getCensusRegister());
            fxEmp.setOutdutyoperatetime(ve.getOutdutyDate());
//        fxEmp.setSchool(ve.getSchool());
//        fxEmp.setProfessional(ve.getProfessional());

            fxEmp.setClothessizeid(ve.getClothesSizeId());
            fxEmp.setCensusregister(ve.getCensusRegister());

            // 设置人员属性
            if (ve.getEmpAttribute() != null && ve.getEmpAttribute().length() > 0) {
                fxEmp.setPeopleattribute(CommonUtils.getPeopleAttr(ve.getEmpAttribute(), zone));
            }
        }

        FxUserinfo fxUser = fxUserinfoService.get(user.getId());
        if (fxUser == null) {
            if (!hasRoleMap) {
                // 注意，用户既找不到岗位映射，又不是优信通旧用户
                return false;
            }
            fxUser = new FxUserinfo();
            fxUser.setIsNewRecord(true);
            fxUser.setIsTaskInsert(true);

            fxUser.setUserid(user.getId());
            fxUser.setEmployeeid(ve.getId());
            fxUser.setUsername(user.getLoginName()); // TODO 设置登录用户名

            // 设置登录密码, 默认 手机号码后六位
            fxUser.setPasswordsalt(user.getSysSalt());
            fxUser.setUserpassword(user.getSysPwd());

            fxUser.setUserstate("2");
            fxUser.setPrintcount("5");
        }

        fxUser.setId(IdGen.uuid());

        List<SysUserrole> sysUserroleList = new ArrayList<SysUserrole>();
        for (ViSysRoleMap roleMap : roleMapList) {
            if (roleMap != null) {
                SysUserrole sysUserrole = new SysUserrole();
                sysUserrole.setRoleid(roleMap.getSysRoleId());
                sysUserrole.setUserid(user.getId());
                sysUserrole.setUserroleid(IdGen.uuid());
                sysUserroleList.add(sysUserrole);
            }
        }

        List<SysUserdealerprivilege> userdealerprivilegeList = new ArrayList<SysUserdealerprivilege>();
        for (ViUserDealerPrivilege viPri: privilegeList) {
            SysUserdealerprivilege sysUserdealerprivilege = new SysUserdealerprivilege();
            sysUserdealerprivilege.setUserid(user.getId());
            sysUserdealerprivilege.setDealerrelationid(viPri.getDealerRelationId());
            sysUserdealerprivilege.setDealerprivilegekind(viPri.getDealerPrivilegeKind());
            sysUserdealerprivilege.setDealerprivilegeid(IdGen.uuid());
            userdealerprivilegeList.add(sysUserdealerprivilege);
        }

        try {
            fxSysService.syncUserToSys(fxEmp, fxUser, sysUserroleList, userdealerprivilegeList, hasRoleMap, ve.getPostName());
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     * 同步员工和用户信息，以及用户角色信息
     */
    private boolean onlyUpdVe(ViEmployee ve, boolean hasRoleMap, String zone) {
        // TODO  同步员工信息
        FxEmployeeinfo fxEmp = null;
        if (hasRoleMap) {
            fxEmp = fxEmployeeinfoService.get(ve.getId());
            if (fxEmp == null) {
                fxEmp = new FxEmployeeinfo();
                fxEmp.setCreatetime(new Date());
                fxEmp.setIsTaskInsert(true);
                fxEmp.setIsNewRecord(true);
            }

            // 设置假的ID, 原来的表里面没有这个字段
            fxEmp.setId(IdGen.uuid());
            fxEmp.setRemark(ve.getRemarks());

            fxEmp.setCompanyid(ve.getComp().getId());
            fxEmp.setDepartmentid(ve.getDept().getId());
            fxEmp.setPositionid(ve.getPost().getId());

            fxEmp.setEmployeeid(ve.getId());

            // 生成员工ID TODO 填写生成规则
            fxEmp.setEmployeecode(ve.getCode());

            fxEmp.setEmployeename(ve.getName());
            // 添加二级前缀
//            fxEmp.setEmployeename(ve.getComp().getName() + ve.getName());

            fxEmp.setSex(ve.getSex());
            fxEmp.setEducationid(ve.getEducateId());

            if (ve.getBirthDate() != null) {
                fxEmp.setAge(String.valueOf(CommonUtils.GetAge(ve.getBirthDate())));
            }
            fxEmp.setBirthdaydate(ve.getBirthDate());
            fxEmp.setMaritalstatus(ve.getMaritalStatus());
            String telephone = ve.getTelephone();
            if (telephone.length() > 11 && telephone.contains("-a")) {
                telephone = ve.getTelephone().substring(0, 11);
            }
            fxEmp.setTelephone(telephone);
            fxEmp.setIndutydate(ve.getIndutyDate());
            fxEmp.setChangeformaldate(ve.getOndutyDate()); // 转正日期字段
            fxEmp.setOutdutydate(ve.getOutdutyDate());
            fxEmp.setEmployeecurrstateid(ve.getCurStateId());
            fxEmp.setIdentitycard(ve.getIdentityCard());
            fxEmp.setAddress(ve.getAddress());
            if (ve.getSp() != null && ve.getSp().getId() != null) {
                fxEmp.setSuperioremployeeid(ve.getSp().getId());
            }

            fxEmp.setEmployeeattribute(ve.getDgAttribute());
            if (StringUtils.isBlank(fxEmp.getEmployeeattribute())) {
                fxEmp.setEmployeeattribute(CommonUtils.getDgAttr(ve.getPostName(), ve.getEmpAttribute()));
            }
            fxEmp.setBirthdaydatetype("1");
            // 设置农历时间 TODO

            fxEmp.setCensusregister(ve.getCensusRegister());
            fxEmp.setOutdutyoperatetime(ve.getOutdutyDate());
//        fxEmp.setSchool(ve.getSchool());
//        fxEmp.setProfessional(ve.getProfessional());

            fxEmp.setClothessizeid(ve.getClothesSizeId());
            fxEmp.setCensusregister(ve.getCensusRegister());

            // 设置人员属性
            if (ve.getEmpAttribute() != null && ve.getEmpAttribute().length() > 0) {
                fxEmp.setPeopleattribute(CommonUtils.getPeopleAttr(ve.getEmpAttribute(), zone));
            }
        }

        boolean updStatus = false;
        try {
            fxSysService.syncVeToSys(fxEmp, hasRoleMap);
            updStatus = true;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return updStatus;
    }

    /**
     * 找到相同的用户信息，然后替换本地员工 信息的ID和用户的ID
     * @param ve
     * @param user
     * @param area
     */
    private boolean findYxtSamePeople(ViEmployee ve, User user, String area, List<ViSysRoleMap> viSysRoleMapList) {
        boolean retFlag = false;

        do {
            if (ve.getIdentityCard() == null || ve.getIdentityCard().length() != 18) {
                continue;
            }

            FxEmployeeinfo fxEmployeeinfo = null;
            FxUserinfo fxUserinfo = null;
            List<FxEmployeeinfo> fxEmployeeinfos = null;

            // 从优信通查询该用户身份证号的员工信息
            try {
                Helper.changeDB(area);
                fxEmployeeinfos = fxEmployeeinfoService.findByIdCardNum(ve.getIdentityCard());
            } catch (Exception e) {
                e.printStackTrace();
                continue;
            } finally {
                DatabaseContextHolder.setMainDb();
            }

            if (fxEmployeeinfos.size() == 0) {
                retFlag = true;
                continue;
            }

            for (FxEmployeeinfo fxEmp : fxEmployeeinfos) {

                // 如果是自己本身，则直接继续运行
                if (ve.getId().equals(fxEmp.getEmployeeid())) {
                    retFlag = true;
                    continue;
                }

                // 查找该ID在系统中是否被其他员工使用， 如果是 则继续下一个
                ViEmployee veTemp = viEmployeeService.get(fxEmp.getEmployeeid());
                if (veTemp != null) {
                    continue;
                } else {
                    fxEmployeeinfo = fxEmp;
                }
            }

            if (fxEmployeeinfo == null) {
                System.out.println("该用户无法正常同步，因为使用该身份证号的用户非唯一！"+ve.getIdentityCard());
                continue;
            }

            // 查找对应的用户信息
            try {
                Helper.changeDB(area);
                fxUserinfo = fxUserinfoService.getByEmpId(fxEmployeeinfo.getEmployeeid());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                DatabaseContextHolder.setMainDb();
            }

            if (fxUserinfo == null) {

                if (viSysRoleMapList.size() == 0) {
                    System.out.println("无法找到该员工的用户信息，身份号码：" + ve.getIdentityCard() + ",fxEmpId:" + fxEmployeeinfo.getEmployeeid());
                    continue;
                }

                fxUserinfo = createNewUser(ve, user, fxEmployeeinfo.getEmployeeid(), viSysRoleMapList, area);
                if (fxUserinfo == null) {
                    continue;
                }

                // 替换本地员工的ID
                // 替换本地用户的ID
                try {
                    systemService.updVivoUserAnEmployeeId(fxEmployeeinfo.getEmployeeid(), ve.getId(), null, user.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("替换员工和用户的ID失败！");
                    continue;
                }
            } else {
                // 替换本地员工的ID
                // 替换本地用户的ID
                try {
                    systemService.updVivoUserAnEmployeeId(fxEmployeeinfo.getEmployeeid(), ve.getId(), fxUserinfo.getUserid(), user.getId());
                } catch (Exception e) {
                    e.printStackTrace();
                    System.out.println("替换员工和用户的ID失败！");
                    continue;
                }
            }

            // 设置新员工和用户ID信息
            ve.setId(fxEmployeeinfo.getEmployeeid());
            user.setId(fxUserinfo.getUserid());
            retFlag = true;
        }while (false);

        return retFlag;
    }


    /**
     * 单纯替换员工UID信息
     * @param ve
     * @param user
     * @param area
     * @return
     */
    private boolean onlyUpdUser(ViEmployee ve, User user, String area, List<ViSysRoleMap> roleMapList) {
        boolean retFlag = false;
        FxUserinfo fxUserinfo = null;

        do {
            // 查找对应的用户信息
            try {
                Helper.changeDB(area);
                fxUserinfo = fxUserinfoService.getByEmpId(ve.getId());
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                DatabaseContextHolder.setMainDb();
            }

            if (fxUserinfo == null) {
                if (roleMapList.size() == 0) {
                    System.out.println("无法找到该员工的用户信息，身份号码：" + ve.getIdentityCard() + ",fxEmpId:" + ve.getId());
                    continue;
                } else {
                    fxUserinfo = createNewUser(ve, user, ve.getId(), roleMapList, area);
                }
            }

            // 未创建成功新用户
            if (fxUserinfo == null) {
                continue;
            }

            // 如果是同一个用户，退出返回
            if (fxUserinfo.getUserid().equals(user.getId())) {
                retFlag = true;
                continue;
            }

            // 替换本地员工的ID
            // 替换本地用户的ID
            try {
                // 更新用户的员工信息
                user.setNewUid(fxUserinfo.getUserid());
                user.setOldUid(user.getId());

                systemService.updVivoUser(user);
            } catch (Exception e) {
                e.printStackTrace();
                System.out.println("替换用户的ID失败！");
                continue;
            }

            // 设置新员工和用户ID信息
            ve.setId(ve.getId());
            user.setId(fxUserinfo.getUserid());
            retFlag = true;
        } while (false);

        return retFlag;
    }

    private FxUserinfo createNewUser(ViEmployee ve, User user, String veId, List<ViSysRoleMap> roleMapList, String area) {
        // 设置新用户密码和密码盐
        if (StringUtils.isBlank(user.getSysSalt()) || StringUtils.isBlank(user.getSysPwd())) {
            String password = ve.getTelephone().substring(5, 11);
            user.setSysSalt(SysUtils.createSalt());
            user.setSysPwd(SysUtils.getPwdBySalt(password, user.getSysSalt()));
        }

        FxUserinfo fxUser = new FxUserinfo();
        fxUser.setIsNewRecord(true);
        fxUser.setIsTaskInsert(true);

        fxUser.setUserid(user.getId());
        fxUser.setEmployeeid(veId);
        fxUser.setUsername(user.getLoginName()); // TODO 设置登录用户名

        // 设置登录密码, 默认 手机号码后六位
        fxUser.setPasswordsalt(user.getSysSalt());
        fxUser.setUserpassword(user.getSysPwd());

        fxUser.setUserstate("2");
        fxUser.setPrintcount("5");


        fxUser.setId(IdGen.uuid());

//        SysUserrole sysUserrole = null;
//        if (roleMap != null) {
//            sysUserrole = new SysUserrole();
//            sysUserrole.setRoleid(roleMap.getSysRoleId());
//            sysUserrole.setUserid(user.getId());
//            sysUserrole.setUserroleid(IdGen.uuid());
//        }

        List<SysUserrole> sysUserroleList = new ArrayList<SysUserrole>();
        for (ViSysRoleMap viSysRoleMap : roleMapList) {
            SysUserrole sysUserrole = new SysUserrole();
            sysUserrole.setRoleid(viSysRoleMap.getSysRoleId());
            sysUserrole.setUserid(user.getId());
            sysUserrole.setUserroleid(IdGen.uuid());
            sysUserroleList.add(sysUserrole);
        }

        try {
            Helper.changeDB(area);
            fxSysService.onlyCreateUser(fxUser, sysUserroleList);
        } catch (Exception e) {
            e.printStackTrace();
            fxUser = null;
        } finally {
            DatabaseContextHolder.setMainDb();
        }

        return fxUser;
    }
}
